﻿using System;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Drawing;

namespace Client.Logic
{
    class Printer
    {
        private Font print_font = new Font("Arial", 12);
        private string[] print_lines = null;
        private int current_line_index = 0;

        public Printer(string text)
        {
            print_lines = text.Split('\n');
        }

        public void Print()
        {
            PrintDocument document = new PrintDocument();

            document.PrintPage += this.PrintPage;

            PrintDialog printer_dlg = new PrintDialog();
            printer_dlg.Document = document;
            printer_dlg.ShowDialog();
            document.PrinterSettings = printer_dlg.PrinterSettings;

            PageSetupDialog page_dlg = new PageSetupDialog();
            page_dlg.Document = document;
            page_dlg.ShowDialog();
            document.DefaultPageSettings = page_dlg.PageSettings;

            PrintPreviewDialog prin_dlg = new PrintPreviewDialog();
            prin_dlg.Document = document;
            prin_dlg.ShowDialog();
        }

        private void PrintPage(object sender, PrintPageEventArgs e)
        {
            Graphics graph = e.Graphics;

            float left_margin = e.MarginBounds.Left;
            float top_margin = e.MarginBounds.Top;
            float y_pos = 0;
            float lines_per_page = 
                e.MarginBounds.Height / print_font.GetHeight(graph);

            StringFormat string_format = new StringFormat();

            while (current_line_index < lines_per_page &&
                   current_line_index < print_lines.Length)
            {
                y_pos = top_margin + current_line_index
                      * print_font.GetHeight(graph);

                graph.DrawString(print_lines[current_line_index],
                                 print_font,
                                 Brushes.Black,
                                 left_margin,
                                 y_pos,
                                 string_format);

                ++current_line_index;
            }

            if (current_line_index == print_lines.Length)
            {
                e.HasMorePages = false;
                current_line_index = 0;
            }
            else
                e.HasMorePages = true;
        }
    }
}
